import praw
import pandas as pd
from datetime import datetime

# Reddit API 认证配置
reddit = praw.Reddit(
    client_id="pssriaTPi3Meega9t1qtQA",
    client_secret="z646_aUk4dsAEc3uMi6qTWKJi5iKWw",
    user_agent="redit:get_snoring:v1"
)

def get_subreddit_posts(subreddit_name, limit=100):
    """获取指定subreddit的帖子"""
    subreddit = reddit.subreddit(subreddit_name)
    
    posts = []
    for post in subreddit.new(limit=limit):  # 可以使用 hot/top/new 等排序方式
        posts.append({
            "title": post.title,
            "author": str(post.author),
            "created_utc": datetime.utcfromtimestamp(post.created_utc),
            "score": post.score,
            "upvote_ratio": post.upvote_ratio,
            "num_comments": post.num_comments,
            "post_id": post.id,
            "content": post.selftext,
            "url": post.url,
            "flair": post.link_flair_text,
            "awards": post.total_awards_received,
            "stickied": post.stickied,
            "spoiler": post.spoiler,
        })
    return posts

def get_post_comments(post_id):
    submission = reddit.submission(id=post_id)
    submission.comments.replace_more(limit=None)
    
    comments = []
    for comment in submission.comments.list():
        comments.append({
            "comment_author": str(comment.author),
            "comment_body": comment.body,
            "comment_score": comment.score,
            "comment_time": datetime.utcfromtimestamp(comment.created_utc)
        })
    return comments

def analyze_posts(df):
    """基础数据分析"""
    # df = pd.DataFrame(posts)
    
    # 简单分析示例
    print(f"总帖子数量: {len(df)}")
    print("\n最高赞帖子:")
    print(df.sort_values('score', ascending=False).head(3)[['title', 'score']])
    
    print("\n最近发帖时间分布:")
    print(df['created_utc'].dt.floor('d').value_counts().head())

    from textblob import TextBlob  # 需要安装textblob

    # 情感分析
    df['sentiment'] = df['content'].apply(lambda x: TextBlob(x).sentiment.polarity)
    print("\n情感分析结果：")
    print(df['sentiment'].describe())

    # 词频统计
    from collections import Counter
    word_counts = Counter(" ".join(df['title']).lower().split())
    print("\n高频关键词：")
    print(word_counts.most_common(10))
    
    return df

if __name__ == "__main__":
    # 配置参数
    TARGET_SUBREDDIT = "snoring"
    POST_LIMIT = 500  # 获取帖子数量
    print("1")

    # 获取数据
    # posts = get_subreddit_posts(TARGET_SUBREDDIT, POST_LIMIT)
    # df = pd.DataFrame(posts)
    print(2)

    df = pd.read_csv(f"{TARGET_SUBREDDIT}_posts.csv")
    
    # 分析数据
    df = analyze_posts(df)
    
    # 保存到CSV
    # df.to_csv(f"{TARGET_SUBREDDIT}_posts.csv", index=False)
    # print(f"\n数据已保存到 {TARGET_SUBREDDIT}_posts.csv")